<template>
  <el-dialog
    :title="props.operType === 'add' ? '新增投放餐品' : '编辑投放餐品'"
    v-model="visible"
    width="60%"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="closeDialog"
  >
    <el-form :model="form" :rules="rules" ref="comboPlanRef" label-width="100px">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>餐品信息</span>
          </div>
        </template>
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="计划名称" prop="cPlanName">
                <el-input v-model="form.cPlanName" placeholder="请输入计划名称" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="投放设备" prop="machineId">
                <div class="select-box">
                  <el-input
                    v-model="form.machineId"
                    placeholder="请选择设备"
                    maxlength="60"
                    readonly
                    clas="input-box"
                  />
                  <el-button
                    :disabled="props.operType === 'edit'"
                    @click="handleAddMachineColumn"
                    type="primary"
                    >选择设备</el-button
                  >
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="投放时间" prop="planTime">
                <el-date-picker
                  style="width: 100%"
                  v-model="form.planTime"
                  :disabled="!form.machineId || props.operType === 'edit'"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                  :disabled-date="disabledDate"
                  @calendar-change="calendarChange"
                  @change="changeDate"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12"> </el-col> -->
          </el-row>
        </div>
      </el-card>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>投放货道餐品信息</span>
            <el-button
              :disabled="!form.machineId || !form.planTime?.length"
              type="primary"
              @click="handleBatchAdd"
              >批量增加</el-button
            >
          </div>
        </template>
        <div v-if="form.machineId && form.planTime">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane
              v-for="(item, index) in selectDataRange"
              :key="index"
              :name="item.day"
              :label="item.week + '\n' + item.day"
            >
              <div class="combo-box">
                <!-- 中吉 4 列 15 行 -->
                <!-- 自研 3 列 8 行 -->
                <!-- 四代机 4 列 9 行 -->
                <div
                  class="combo-box-item"
                  :style="{ width: form.machineType == 2 || form.machineType == 4 ? '23%' : '32%' }"
                  v-for="(itemRow, indexRow) in comboRoadDrfaultData[index]"
                  :key="indexRow"
                >
                  <div class="title-box">
                    <div v-if="form.machineType == 2 || form.machineType == 4"
                      >货道号：{{
                        Math.ceil((indexRow + 1) / 4) +
                        '' +
                        ((indexRow + 1) % 4 === 0 ? 4 : (indexRow + 1) % 4)
                      }}</div
                    >
                    <div v-else
                      >货道号：{{
                        Math.ceil((indexRow + 1) / 3) +
                        '' +
                        ((indexRow + 1) % 3 === 0 ? 3 : (indexRow + 1) % 3)
                      }}</div
                    >
                    <div class="oper-box">
                      <span class="operadd" @click="handleAddComboColumn(indexRow)">添加</span>
                      <span class="operclear" @click="handleRemoveComboColumn(indexRow)">清空</span>
                    </div>
                  </div>
                  <div>
                    <el-input v-model="itemRow.showText" readonly placeholder="请添加套餐" />
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div v-else class="no-content">
          <img src="@/assets/images/noContent.png" class="no-img" />
          <label class="no-box">
            <span>{{ !form.machineId ? '请先选择设备' : '请选择投放时间' }}</span></label
          >
        </div>
      </el-card>
      <el-card class="box-card" v-if="comboStatistics">
        <template #header>
          <div class="card-header">
            <span>餐品信息统计</span>
          </div>
        </template>
        <div class="content-box">
          <el-descriptions title="" :column="4">
            <el-descriptions-item v-for="(item, index) in comboStatistics" :key="index"
              >{{ item.comboName + ' * ' + item.comboNum }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-card>
      <el-card class="box-card" v-if="enterpriseOrderSummary.length">
        <template #header>
          <div class="card-header">
            <span>酒店提交餐品信息统计</span>
          </div>
        </template>
        <div class="content-box">
          <el-descriptions title="" :column="4">
            <el-descriptions-item v-for="(item, index) in enterpriseOrderSummary" :key="index"
              >{{ item.comboName + ' * ' + item.comboNum }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-card>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loadingSubmit">{{
          props.operType === 'add' ? '新增' : '更新'
        }}</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="addVisible"
    :close-on-click-modal="false"
    title="批量投放货道选择"
    width="600px"
    append-to-body
    @close="onClose"
  >
    <table>
      <div class="_table">
        <tr class="head_tr">
          <div class="_allCheckbox">
            <el-checkbox v-model="allCheckbox" @change="allClick" size="large"
          /></div>
          <th v-for="(item, index) in colChecked[form?.machineType]" :key="item.col">
            <el-checkbox
              v-model="item.checked"
              @change="(val) => colClick(index, val)"
              size="large"
            />
          </th>
        </tr>
        <tr class="body_tr" v-for="(item, index) in list" :key="index">
          <div class="_rowChecked">
            <el-checkbox
              v-model="rowChecked[form?.machineType][index].checked"
              @change="rowClick(index, rowChecked[form?.machineType][index])"
              size="large"
            />
          </div>
          <td
            :style="{
              background: combo.isSelected ? '#E3F1FF' : '#fff'
            }"
            class="_td"
            v-for="combo in item"
            :key="combo.roadNumber"
            @click.stop="oneClick(combo)"
          >
            {{ combo.roadNumber }}
          </td>
        </tr>
      </div>
    </table>
    <template #footer>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" :disabled="_disabled" @click="handleAction"> 确认 </el-button>
    </template>
  </el-dialog>

  <machineModule
    ref="machineModuleRef"
    :machindData="machindData"
    :resetDeviceSelection="resetDeviceSelection"
    @selectedMachindData="getSelectMachineData"
  />
  <comboModule
    ref="comboModuleRef"
    :isTableOpen="isTableOpen"
    @renderChecked="renderChecked"
    @selectedComboData="getSelectComboData"
  />
</template>

<script setup>
import { ElMessageBox } from 'element-plus'
import { defineProps } from 'vue'
import {
  addComboPlanDevote,
  updateComboPlanDevote,
  getComboMachineInfo,
  getComboRoadInfo
} from '@/api/devote'
import machineModule from './selectmachine.vue'
import comboModule from './selectcombo.vue'
import { formatDate } from '@/utils/index'
import { postPackageDataSummaryApi } from '@/api/order'
import { handProjectList } from '@/utils/tools'

const props = defineProps({
  operType: {
    type: String,
    default: 'add'
  },
  adTypeOptions: {
    type: Array,
    default: () => []
  },
  planId: {
    type: String,
    default: null
  }
})

const emit = defineEmits(['updateList'])
const { proxy } = getCurrentInstance()
const visible = ref(false)
const loadingSubmit = ref(false)
const comboPlanRef = ref()

//** 时间范围控制 */
const selectDataRange = ref([])
const activeName = ref('')
const firstChooseDate = ref('')

const disabledDate = (time) => {
  const currentDate = new Date().setHours(0, 0, 0, 0)

  const endTime = new Date(groupPlanLaunchTime.value.endTime)
  const startTime = new Date(groupPlanLaunchTime.value.startTime)

  // 只能在默认范围内选择
  if (time.getTime() < startTime || time.getTime() > endTime) {
    // console.log('4', 4)
    return true
  }

  if (time.getTime() < currentDate) {
    // console.log('1', 1)
    return true
  } else {
    if (firstChooseDate.value) {
      const timeRange = 1 * 24 * 60 * 60 * 1000 // 1天时间戳
      const minTime = firstChooseDate.value - timeRange * 6
      const maxTime = firstChooseDate.value + timeRange * 6
      return time.getTime() > maxTime || time.getTime() < minTime
    } else {
      return false
    }
  }
}
const calendarChange = (val) => {
  firstChooseDate.value = val[0].getTime() //点击第一次选中日期
  if (val[1]) firstChooseDate.value = '' // 选中后必须清空

  const startDate = new Date(val[0])
  const endDate = new Date(val[1])
  handleDataRange(startDate, endDate)
}
const handleDataRange = (startDate, endDate) => {
  const dates = []
  let currentDate = new Date(startDate)
  while (currentDate <= endDate) {
    const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

    const dayOfWeek = weekDays[currentDate.getDay()]
    const year = currentDate.getFullYear()
    const month = currentDate.getMonth() + 1
    const day = currentDate.getDate()
    const formattedDate = { week: dayOfWeek, day: `${year}-${zeroFill(month)}-${zeroFill(day)}` }
    dates.push(formattedDate)
    currentDate.setDate(currentDate.getDate() + 1)
  }
  selectDataRange.value = dates
  if (selectDataRange.value.length > 0) {
    activeName.value = selectDataRange.value[0].day
  }
  //时间范围变化，货道信息重置
  comboRoadDrfaultData.value = []
  staticComboData()
}
const zeroFill = (num) => {
  return num < 10 ? '0' + num : num
}
function handleClick(event) {
  activeName.value = event.props.name
  staticComboData()
}

//** form定义 */
const form = ref({
  cPlanName: null,
  machineType: null,
  startTime: null,
  endTime: null,
  machineId: null,
  planTime: null,
  cityName: null
})
const rules = {
  cPlanName: [{ required: true, message: '计划名称不能为空', trigger: 'blur' }],
  machineId: [{ required: true, message: '投放设备不能为空', trigger: ['blur', 'change'] }],
  planTime: [{ required: true, message: '投放时间不能为空', trigger: 'change' }]
}

const colChecked = ref({
  2: [
    { col: '第一列', checked: false },
    { col: '第二列', checked: false },
    { col: '第三列', checked: false },
    { col: '第四列', checked: false }
  ],
  3: [
    { col: '第一列', checked: false },
    { col: '第二列', checked: false },
    { col: '第三列', checked: false }
  ],
  4: [
    { col: '第一列', checked: false },
    { col: '第二列', checked: false },
    { col: '第三列', checked: false },
    { col: '第四列', checked: false }
  ],
  5: [
    { col: '第一列', checked: false },
    { col: '第二列', checked: false },
    { col: '第三列', checked: false }
  ]
})
const rowChecked = ref({
  2: [
    { row: 1, checked: false },
    { row: 2, checked: false },
    { row: 3, checked: false },
    { row: 4, checked: false },
    { row: 5, checked: false },
    { row: 6, checked: false },
    { row: 7, checked: false },
    { row: 8, checked: false },
    { row: 9, checked: false },
    { row: 10, checked: false },
    { row: 11, checked: false },
    { row: 12, checked: false },
    { row: 13, checked: false },
    { row: 14, checked: false },
    { row: 15, checked: false }
  ],
  3: [
    { row: 1, checked: false },
    { row: 2, checked: false },
    { row: 3, checked: false },
    { row: 4, checked: false },
    { row: 5, checked: false },
    { row: 6, checked: false },
    { row: 7, checked: false },
    { row: 8, checked: false }
  ],
  4: [
    { row: 1, checked: false },
    { row: 2, checked: false },
    { row: 3, checked: false },
    { row: 4, checked: false },
    { row: 5, checked: false },
    { row: 6, checked: false },
    { row: 7, checked: false },
    { row: 8, checked: false },
    { row: 9, checked: false }
  ],
  5: [
    { row: 1, checked: false },
    { row: 2, checked: false },
    { row: 3, checked: false },
    { row: 4, checked: false },
    { row: 5, checked: false },
    { row: 6, checked: false },
    { row: 7, checked: false },
    { row: 8, checked: false },
    { row: 9, checked: false },
    { row: 10, checked: false },
    { row: 11, checked: false },
    { row: 12, checked: false }
  ]
})
const _disabled = ref(true)
const isTableOpen = ref(false)
const allCheckbox = ref(false)
const list = ref()

watch(
  () => list.value,
  (newVal) => {
    const list = newVal.flat()
    const isSome = list.some((item) => item.isSelected)
    const isEvery = list.every((item) => item.isSelected)
    let colList = colChecked.value[form.value.machineType]
    let rowList = rowChecked.value[form.value.machineType]
    // console.log(isSome)
    // console.log(isEvery)
    isSome ? (_disabled.value = false) : (_disabled.value = true)
    if (!isSome) {
      allCheckbox.value = false
      colChecked.value[form.value.machineType] = colList.map((item) => {
        return { ...item, checked: false }
      })
      rowChecked.value[form.value.machineType] = rowList.map((item) => {
        return { ...item, checked: false }
      })
    } else if (isEvery) {
      allCheckbox.value = true
      colChecked.value[form.value.machineType] = colList.map((item) => {
        return { ...item, checked: true }
      })
      rowChecked.value[form.value.machineType] = rowList.map((item) => {
        return { ...item, checked: true }
      })
    } else if (isSome) {
      allCheckbox.value = false
      let rowList = []
      let sumList = []
      newVal.forEach((arrItem, arrIndex) => {
        const isArrItem = arrItem.every((item) => item.isSelected)
        // console.log(isArrItem)
        if (isArrItem) {
          rowList.push({ item: arrIndex, flag: true })
        } else {
          rowList.push({ item: arrIndex, flag: false })
        }
        arrItem.forEach((item, index) => {
          if (item.isSelected) {
            sumList.push({ roadNumber: item.roadNumber, index: index + 1 })
          }
        })
      })
      // console.log(sumList)
      if (sumList.length > 0) {
        colChecked.value[form.value.machineType].forEach((colItem, colIndex) => {
          const count = countOccurrences(sumList, colIndex + 1)
          count === rowChecked.value[form.value.machineType].length
            ? (colItem.checked = true)
            : (colItem.checked = false)
        })
      }
      // console.log(rowList)
      if (rowList.length > 0) {
        rowChecked.value[form.value.machineType].forEach((item, index) => {
          rowList.map((rowItem) => {
            if (rowItem.item === index) {
              item.checked = rowItem.flag
            }
          })
        })
      }
    }
  },
  {
    deep: true
  }
)
/**判断是否满足行列 */
function countOccurrences(list, targetIndex) {
  return list.filter((item) => item.index === targetIndex).length
}
/**点击某一行 */
const rowClick = (index, item) => {
  operationChecked({ checked: item.checked, type: '行', num: index })
}
/** 点击某一列 */
const colClick = (_index, checked) => {
  operationChecked({ checked: checked, type: '列', num: _index })
}

/**点击某一个 */
const oneClick = (item) => {
  operationChecked({ checked: item.isSelected ? false : true, type: '单', num: item.roadNumber })
}

/**全选 */
const allClick = (checked) => {
  operationChecked({ checked })
}
/**关闭相应的数据展示 */
function operationChecked({ checked, type, num }) {
  console.log(checked, type, num)
  if (type === '行') {
    list.value[num].forEach((item) => {
      item.isSelected = checked
    })
  } else if (type === '列') {
    list.value = list.value.map((arrItem) => {
      return arrItem.map((item, index) => {
        if (index === num) {
          return { ...item, isSelected: checked }
        }
        return item
      })
    })
  } else if (type === '单') {
    list.value.forEach((arrItem) => {
      const _index = arrItem.findIndex((item) => item.roadNumber === num)
      if (_index !== -1) {
        arrItem[_index].isSelected = checked
      }
    })
  } else {
    list.value = list.value.map((arrItem) =>
      arrItem.map((item) => {
        return { ...item, isSelected: checked }
      })
    )
  }
}

/** 设备选择 */
function handleAddMachineColumn() {
  resetDeviceSelection.value = false
  proxy.$refs.machineModuleRef.handleAddFileColumn(form.value.cityName)
}
const tableList = ref([])
function getSelectMachineData(selected, machineType) {
  tableList.value = selected
  let arr = tableList.value.map((ele) => ele.machineName)
  form.value.machineId = arr.join(',')
  if (machineType !== echoSelectType.value) {
    form.value.machineType = machineType
    form.value.planTime = null
    comboRoadDrfaultData.value = []
    comboStatistics.value = []
  } else {
    form.value.machineType = echoSelectType.value
    comboRoadDrfaultData.value = echoSelectRoad.value
    if (props.operType !== 'add') {
      staticComboData()
    }
  }
}

const currDateIndex = computed(() => {
  let index = selectDataRange?.value?.findIndex((ele) => ele.day === activeName.value)
  return index
})

//** 套餐选择 */
const addCurrentRoadIndex = ref(null)
const comboStatistics = ref(null)
const enterpriseOrderSummary = ref([])
function handleAddComboColumn(addIndex) {
  addCurrentRoadIndex.value = addIndex
  proxy.$refs.comboModuleRef.handleAddFileColumn(form.value.cityName)
}

function getSelectComboData(selected) {
  if (isTableOpen.value) {
    isTableOpen.value = false
  }
  console.log(selected)
  if (!selected) return

  comboRoadDrfaultData.value.forEach((ele, index) => {
    if (index == currDateIndex.value) {
      ele[addCurrentRoadIndex.value].comboId = selected.comboId
      ele[addCurrentRoadIndex.value].comboName = selected.name
      ele[addCurrentRoadIndex.value].comboNum = form.value.machineType == 2 ? 1 : 3
      ele[addCurrentRoadIndex.value].showText =
        ele[addCurrentRoadIndex.value].comboName + ' * ' + ele[addCurrentRoadIndex.value].comboNum
    }
  })
  //餐品统计
  staticComboData()
}
function handleRemoveComboColumn(delIndex) {
  comboRoadDrfaultData.value.forEach((ele, index) => {
    if (index == currDateIndex.value) {
      ele[delIndex].comboId = null
      ele[delIndex].comboName = null
      ele[delIndex].comboNum = null
      ele[delIndex].showText = null
    }
  })
  //餐品统计
  staticComboData()
}
/** 餐品统计*/
const staticComboData = () => {
  const comboIdMap = new Map()

  comboRoadDrfaultData.value.forEach((arr) => {
    arr.forEach((obj) => {
      if (obj.comboId && obj.date === activeName.value) {
        if (!comboIdMap.has(obj.comboId)) {
          comboIdMap.set(obj.comboId, { ...obj })
        } else {
          const storedObj = comboIdMap.get(obj.comboId)
          storedObj.comboNum = parseInt(storedObj.comboNum)
          obj.comboNum = parseInt(obj.comboNum)
          storedObj.comboNum += obj.comboNum
        }
      }
    })
  })

  comboStatistics.value = Array.from(comboIdMap.values())
}

//** 投放货道餐品信息 */
const comboRoadDrfaultData = ref([])
const changeDate = () => {
  comboRoadDrfaultData.value = []
  for (let i = 0; i < selectDataRange.value.length; i++) {
    let childs = []
    const machineType = form.value.machineType
    let len = machineType == 2 ? 60 : machineType == 3 ? 24 : 36
    for (let j = 0; j < len; j++) {
      let obj = {
        roadNumber:
          machineType == 2 || machineType == 4
            ? Math.ceil((j + 1) / 4) + '' + ((j + 1) % 4 === 0 ? 4 : (j + 1) % 4)
            : Math.ceil((j + 1) / 3) + '' + ((j + 1) % 3 === 0 ? 3 : (j + 1) % 3),
        comboNum: null,
        comboId: null,
        date: selectDataRange.value[i].day,
        comboName: '',
        showText: ''
      }
      childs.push(obj)
    }
    comboRoadDrfaultData.value.push(childs)
  }
  console.log('投放货道餐品信息', comboRoadDrfaultData.value)
}

const resetDeviceSelection = ref(false)
function closeDialog() {
  visible.value = false
  resetDeviceSelection.value = true
  enterpriseOrderSummary.value = []
}
//** 提交*/
function submitForm() {
  proxy.$refs['comboPlanRef'].validate((valid) => {
    if (valid) {
      loadingSubmit.value = true
      //货道套餐
      const finallyComboRoadData = []
      comboRoadDrfaultData.value.forEach((element) => {
        element.forEach((obj) => {
          if (obj.comboId) {
            const newObj = {
              comboNum: obj.comboNum,
              comboId: obj.comboId,
              roadNumber: obj.roadNumber,
              date: getTimestamp(obj.date)
            }
            finallyComboRoadData.push(newObj)
          }
        })
      })
      const params = {
        cplanName: form.value.cPlanName,
        startTime: getTimestamp(form.value.planTime[0]),
        endTime: getTimestamp(form.value.planTime[1]),
        machineType: form.value.machineType,
        planId: props.planId,
        machineList: tableList.value.map((ele) => {
          return { machineId: ele.machineId }
        }),
        comboRoad: finallyComboRoadData,
        cityName: form.value.cityName
      }
      if (props.operType === 'add') {
        addComboPlanDevote(params).then(
          (res) => {
            proxy.$modal.msgSuccess('新增成功')
            emit('updateList')
            visible.value = false
          },
          (error) => {
            loadingSubmit.value = false
          }
        )
      } else {
        ElMessageBox.confirm('确认要修改这行数据吗?', '系统提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          center: false
        })
          .then(() => {
            delete params.planId
            updateComboPlanDevote({
              ...params,
              cplanId: currentId.value,
              machineList: form.value.machineList,
              status: status.value
            }).then((res) => {
              proxy.$modal.msgSuccess('更新成功')
              emit('updateList')
              visible.value = false
            })
          })
          .catch(() => {
            loadingSubmit.value = false
          })
      }
    }
  })
}

//** init */
const currentId = ref()
const status = ref()
const echoSelectType = ref(null)
const echoSelectRoad = ref(null)
const groupPlanLaunchTime = ref(null)
function show(type, data, groupPlanTimeData) {
  groupPlanLaunchTime.value = groupPlanTimeData //计划组投放时间范围
  reset()
  visible.value = true
  if (type === 'edit' || type === 'copy') {
    status.value = data.status
    form.value = {
      cplanId: data.cplanId,
      cPlanName: data.cplanName,
      machineType: data.machineType,
      startTime: formatDate(data.startTime),
      endTime: formatDate(data.endTime),
      planTime: [formatDate(data.startTime), formatDate(data.endTime)],
      machineList: null,
      cityName: data.cityName
    }
    echoSelectType.value = data.machineType
    getDetailData(data.cplanId)
    currentId.value = data.cplanId
  }
  form.value.cityName = data.cityName
}

function getEnterpriseOrderSummaryList(machineId) {
  console.log(machineId)
  postPackageDataSummaryApi({ machineId }).then((res) => {
    enterpriseOrderSummary.value = res.data
  })
}

//** 获取设备信息，货道餐品信息 */
const machindData = ref(null)
function getDetailData(id) {
  let startDate = form.value.startTime
  let endDate = form.value.endTime
  handleDataRange(getTimestamp(startDate), getTimestamp(endDate))
  changeDate()
  getComboMachineInfo(id).then((res) => {
    console.log('根据餐品计划id获取设备信息', res)
    getEnterpriseOrderSummaryList(res.data[0].machineId)
    let nameArr = res.data.map((ele) => (ele.deviceName ? ele.deviceName : ele.machineId))
    form.value.machineId = nameArr.join(',')
    form.value.machineList = res.data.map((item) => {
      return {
        machineId: item.machineId,
        machineName: item.deviceName
      }
    })
    tableList.value = form.value.machineList
    machindData.value = {
      machineType: form.value.machineType,
      machineList: res.data
    }
  })

  getComboRoadInfo(id).then((res) => {
    console.log('根据餐品计划id获取货道餐品信息', res)
    let arr = res?.data || []

    arr.forEach((item) => {
      let dateIndex = comboRoadDrfaultData.value.findIndex(
        (ele) => ele[0].date === formatDate(item.date).slice(0, 10)
      )
      if (dateIndex > -1) {
        let roadIndex = comboRoadDrfaultData.value[dateIndex].findIndex(
          (o) => o.roadNumber === item.roadNumber
        )
        if (roadIndex > -1) {
          comboRoadDrfaultData.value[dateIndex][roadIndex] = item
          comboRoadDrfaultData.value[dateIndex][roadIndex].showText =
            item.comboName + ' * ' + item.comboNum
          comboRoadDrfaultData.value[dateIndex][roadIndex].date = formatDate(item.date).slice(0, 10)
        }
      }
    })
    staticComboData()
  })
  echoSelectRoad.value = comboRoadDrfaultData.value
}

function getTimestamp(dateStr) {
  return new Date(dateStr).getTime()
}
function reset() {
  form.value = {
    cPlanName: null,
    machineType: null,
    startTime: null,
    endTime: null,
    comboRoad: null,
    machineList: null,
    machineId: null,
    planTime: null
  }
  comboStatistics.value = null
  machindData.value = null
  if (comboPlanRef.value) {
    comboPlanRef.value.resetFields()
  }
  loadingSubmit.value = false
}

const addVisible = ref(false)

function handleBatchAdd() {
  addVisible.value = true

  const machineType = Number(form.value.machineType)
  console.log(list.value)
  list.value = handProjectList(machineType).map((itemArr) =>
    itemArr.map((ev) => ({ roadNumber: ev, isSelected: false }))
  )
  console.log('handleBatchAdd', list.value)
}

function handleAction() {
  proxy.$refs.comboModuleRef.handleAddFileColumn(form.value.cityName)
  isTableOpen.value = true
  addVisible.value = false
}
function onClose() {
  allCheckbox.value = false

  addVisible.value = false
}
/**批量选择操作 */
function renderChecked(ev) {
  if (isTableOpen.value) {
    isTableOpen.value = false
  }
  let arrList = list.value.flat()
  arrList = arrList.filter((item) => item.isSelected)

  comboRoadDrfaultData.value[currDateIndex.value].forEach((ele) => {
    const match = arrList.find((item) => item.roadNumber === ele.roadNumber)
    if (match) {
      ele.comboId = ev.comboId
      ele.comboName = ev.name || ev.comboName
      ele.comboNum = form.value.machineType == 2 ? 1 : 3
      ele.showText = ele.comboName + ' * ' + ele.comboNum
    }
    // 覆盖旧数据
    // else {
    //   ele.comboId = ''
    //   ele.comboName = ''
    //   ele.comboNum = ''
    //   ele.showText = ''
    // }
  })
  staticComboData()
}
defineExpose({
  show
})
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 10px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.select-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .input-box {
    width: 80%;
  }
}
.combo-box {
  width: 100%;
  padding: 10px;
  max-height: 300px;
  overflow-y: auto;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  .combo-box-item {
    width: 23%;
    margin-bottom: 15px;
    border: 1px solid #dedede;
    border-radius: 6px;
    padding: 8px;
    .title-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 30px;
      .oper-box {
        width: 45%;
        display: flex;
        justify-content: flex-end;
        .operadd {
          cursor: pointer;
          color: var(--el-color-primary);
        }
        .operclear {
          margin-left: 8px;
          cursor: pointer;
          color: var(--el-color-danger);
        }
      }
    }
  }
}
.no-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  height: 190px;
  .no-img {
    max-width: 100%;
    max-height: 100%;
  }
  .no-box {
    margin-top: 10px;
  }
}
.content-box {
  width: 100%;
  height: auto;
  min-height: 100px;
}
:deep(.el-tabs) {
  --el-tabs-header-height: 20px;
}
:deep(.el-tabs__header) {
  background-color: #f5f7fa;
}
:deep(.el-tabs__item) {
  text-align: center;
  line-height: 6px;
}
:deep(.el-tabs__nav-next, .el-tabs__nav-prev) {
  background-color: #e4e7ed;
  color: #999093;
  width: 20px;
  text-align: center;
}
:deep(.el-tabs__nav-prev) {
  background-color: #e4e7ed;
  color: #999093;
  width: 20px;
  text-align: center;
}
._table {
  border-bottom: 1px solid #999;
}

.head_tr,
.body_tr {
  display: flex;
  align-items: center;
}

.head_tr th,
.body_tr ._td,
._allCheckbox,
._rowChecked {
  box-sizing: border-box;
  width: 70px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border-left: 1px solid #999;
  border-top: 1px solid #999;
}
._td:last-child,
th:last-child {
  border-right: 1px solid #999;
}
._rowChecked:last-child {
  border-bottom: 1px solid #999;
}
.head_tr th {
  color: #333;
  font-weight: bold;
}

.body_tr ._td {
  color: #666;
  font-size: 16px;
  cursor: pointer;
}
</style>
